<template>
<div class="time-slot">
    <input class="form-control form-control-inline time-slot-input" :name="name" style="cursor: text;" :value="value" :id="id" readonly="readonly" @blur="pickerHide" @focus="pickerShow"  type="text">

    <div class="time-slot-picker " v-show="showPicker" :id="id+'-picker'" @blur="pickerHide">
        <div>
            <table class="border-collapse">
                <thead>
                    <tr>
                        <th class="prev" style="visibility: visible;" @click="datePrev"><i class="fa fa-angle-left"></i></th>
                        <th colspan="5" class="day">{{date.toLocaleDateString()}}</th>
                        <th class="next" style="visibility: visible;" @click="dateNext"><i class="fa fa-angle-right"></i></th>
                    </tr>
                    <tr>
                        <td colspan="3">{{startIndex!=-1?(startDate+' '+times[startIndex]):''}}</td>
                        <td colspan="1">-</td>
                        <td colspan="3">{{endIndex!=-1?(endDate+' '+times[endIndex]):''}}</td>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="row in rows">
                        <td v-for="col in cols" @click="select(row*cols+col)" :class="{old:timeStatus[row*cols+col]==-1,range:timeStatus[row*cols+col]==10,start:timeStatus[row*cols+col]==11,disabled:(timeStatus[row*cols+col]==11&&onlyEnd),end:timeStatus[row*cols+col]==12}">
                            {{times[row*cols+col]}}
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5"></td>
                        <td><a href="javascript:;" style="margin-top:10px;"  @focus="actionFocus"  @click="showPicker=false" data-action="close" class="btn btn-xs default">关闭</a></td>
                        <td colspan="1">
                            <a href="javascript:;" style="margin-top:10px;" @focus="actionFocus"  @click="handle" data-action="close" class="btn btn-xs blue">确定</a>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
</template>
<script>

export default{
    props:{
        id:{
            type: String,
            default: ''
        },
        name:{
            type:String,
            default: ''
        },
        onlyEnd:{
            type: Boolean,
            default: false
        },
        begin:{
            type: String,
            default: ''
        },
        end:{
            type: String,
            default: ''
        },
        value:{
            type:String,
            twoWay: true,
            default: ''
        },
        occupyTimes:{
            type:Array,
            default: function(){
                return []
            }
        }
    },
    data(){
        return{
            showPicker : false,
            date: new Date(),
            times:['00:00','00:30','01:00','01:30','02:00','02:30','03:00','03:30','04:00','04:30','05:00','05:30','06:00','06:30','07:00','07:30','08:00','08:30','09:00','09:30',
                    '10:00','10:30','11:00','11:30','12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30','16:00','16:30','17:00','17:30','18:00','18:30','19:00',
                    '19:30','20:00','20:30','21:00','21:30','22:00','22:30','23:00','23:30'],
            timeStatus:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], //-1:不能选择,0:可以选择,10：range,11:start,12:end
            timeTempStatus: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
            startIndex: -1,
            startDate: null,
            endDate: null,
            endIndex: -1,
            rows:7,
            cols:7,
            startClick: false,
            currentDate: false,
            flagDate: '',
        }
    },
    created(){
        
    },
    methods:{
        handle(){
            this.showPicker = false
            this.value = (this.startIndex!=-1?(this.startDate+' '+this.times[this.startIndex]):'')+'~'+(this.endIndex!=-1?(this.endDate+' '+this.times[this.endIndex]):'')
            console.log(this.endIndex!=-1?(this.endDate+' '+this.times[this.endIndex]):'')

            this.$nextTick(()=>{
                this.showPicker = false
            })
        },

        pickerShow(e){
            console.log('show')
            this.showPicker = false

            if($(e.target).closest('#'+this.id+'-picker').length > 0 || $(e.target).attr('id') == this.id ){
                this.showPicker = true
            }else{
                this.showPicker = false
            }

            this.timeStatus = this.initStatus()
        },

        refresh(){

        },

        actionFocus(e){
            $(e.target).blur()
        },

        pickerHide(e){
            console.log('hide')
            console.log(e)
            // this.showPicker = false

            console.log('333')
        },

        datePrev(){
            this.date = new Date( this.date.setDate(this.date.getDate()-1))
            this.$nextTick(()=>{
                this.timeTempStatus = this.initStatus()
                this.timeStatus = this.initStatus()
            })
        },

        dateNext(){
            this.date = new Date( this.date.setDate(this.date.getDate()+1))
            this.$nextTick(()=>{
                this.timeTempStatus = this.initStatus()
                this.timeStatus = this.initStatus()
            })
        },

        select(index){
            console.log(index+','+this.times[index])

            if(this.timeStatus[index]==-1 || !this.times[index]){
                return
            }

            if(this.onlyEnd){

                if(this.startIndex == index && (this.date.getFullYear()+'-'+(this.date.getMonth()+1)+'-'+this.date.getDate() == this.startDate)) return

                this.setTimeStatus(index,12)
                this.endIndex = index
                this.endDate = this.date.getFullYear()+'-'+(this.date.getMonth()+1)+'-'+this.date.getDate()

                this.timeStatus = this.initStatus()
            }else{
                if(!this.startClick){
                    //选择开始时间的时候，先初始化时间

                    this.timeTempStatus = this.initStatus()
                    this.timeStatus = this.initStatus()

                    console.log('startClick')

                    if(this.endIndex != index){
                        this.startIndex = index
                        this.startDate = this.date.getFullYear()+'-'+(this.date.getMonth()+1)+'-'+this.date.getDate()
                        this.endIndex = -1
                        

                        this.setStartClickStatus(index)
                    }else{
                        this.endIndex = -1
                    }

                    
                    this.timeStatus = this.initStatus()
                    this.startClick = true
                    
                }else{
                    console.log('endClick')
                    if(this.startIndex == index){
                        this.setTimeStatus(index,0)

                        this.startIndex = -1
                        this.endIndex = -1

                        this.timeStatus = this.initStatus()
                        
                    }else if(this.endIndex == index){

                        this.endIndex = -1

                        this.timeStatus = this.initStatus()
                    }else{

                        this.setTimeStatus(index,12)
                        this.endIndex = index
                        this.endDate = this.date.getFullYear()+'-'+(this.date.getMonth()+1)+'-'+this.date.getDate()

                        this.timeStatus = this.initStatus()
                    }

                    this.startClick = false
                }
            }

            
        },
        setStartClickStatus(index){
            let i = 0;

            for(;i<index;i++){
                this.setTimeStatus(i,-1)
            }
            this.setTimeStatus(i,11)
            i++

            for(;i<48;i++){
                if(this.timeStatus[i] == -1){
                    break
                }
            }

            if(i<48){
                this.setTimeStatus(i,0)

                i++

                for(;i<48;i++){
                    this.setTimeStatus(i,-1)
                }
            }
        },
        initStatus(){
            console.log('startIndex:'+this.startIndex+',endIndex:'+this.endIndex)
            
            let now = new Date()
            let dateYear = this.date.getFullYear()
            let dateMonth = this.date.getMonth()+1
            let dateDay = this.date.getDate()
            let dateHour = this.date.getHours()
            let dateMinute = this.date.getMinutes()
            let nowYear = now.getFullYear()
            let nowMonth = now.getMonth() +1
            let nowDay = now.getDate()
            let nowHour = now.getHours() 
            let nowMinute = now.getMinutes()

            let arr = []

            //比较日期
            if(new Date(dateYear,dateMonth-1,dateDay).getTime() < new Date(nowYear,nowMonth-1,nowDay).getTime()){
                for(let i=0;i<48;i++){
                    arr.push(-1)
                }
            }else if(new Date(dateYear,dateMonth-1,dateDay).getTime() > new Date(nowYear,nowMonth-1,nowDay).getTime()){

                for(let i=0;i<48;i++){
                    arr.push(0)
                }
            }else{
                let i=0

                for(;i<=nowHour*2;i++){
                    arr.push(-1)
                }

                if(nowMinute > 30){
                    arr.push(-1)
                    i++
                }
                for(;i<48;i++){
                    arr.push(0)
                }

                // arr.push(-1)
            }

            //设置被占用的时间

            let occupytime = []
            let occupydate = ''

            if(this.startIndex == -1){
                console.log('开始点击前')
                occupytime = []
                for(let i=0;i<this.occupyTimes.length;i++){

                    if(this.createDate(this.occupyTimes[i].date).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()){
                        occupytime = this.occupyTimes[i].times
                        break
                    }
                }

                for(let i=0;i<occupytime.length;i++){

                    let timeArray = occupytime[i].split(':')
                    let hour = parseInt(timeArray[0])
                    let mi = parseInt(timeArray[1])

                    if(mi>=30){
                        arr[hour*2+1] = -1
                    }else{
                        arr[hour*2] = -1
                    }
                }
            }
            
            if(this.startIndex != -1 && this.endIndex == -1){
                console.log('点击开始')
                console.log(arr)
                //只选择了开始时间

                occupytime = []
                //开始时间与当前时间比较
                if(this.createDate(this.startDate).getTime() > new Date(dateYear,dateMonth-1,dateDay).getTime()){
                    for(let i=0;i<arr.length;i++){
                        arr[i] = -1
                    }
                }else if(this.createDate(this.startDate).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()){
                    this.currentDate = false

                    for(let i=0;i<this.startIndex;i++){
                        arr[i] = -1
                    }

                    
                    arr[this.startIndex] = 11

                    occupydate = this.startDate
                    //找出第一个被占用的时间
                    for(let i=0;i<this.occupyTimes.length;i++){ //第一个被占用的天

                        if(this.createDate(this.occupyTimes[i].date).getTime() == this.createDate(occupydate).getTime()){
                            
                            occupytime = this.occupyTimes[i].times
                            break;
                        }
                    }

                    //todo: 占用时间在当天为空的情况

                    for(let i=0;i<occupytime.length;i++){ //被占用的时间

                        let timeArray = occupytime[i].split(':')
                        let hour = parseInt(timeArray[0])
                        let mi = parseInt(timeArray[1])

                        let startTimeArray = this.times[this.startIndex].split(':')
                        let startHour = parseInt(startTimeArray[0])
                        let startMi = parseInt(startTimeArray[0])

                        if(hour> startHour){
                            let i =0

                            if(mi>30){
                                i = hour*2+2
                            }else{
                                i = hour*2+1
                            }

                            for(;i<arr.length;i++){
                                arr[i] = -1
                            }

                            this.currentDate = true

                            break
                        }
                    }
                }else if(this.createDate(this.startDate).getTime() < new Date(dateYear,dateMonth-1,dateDay).getTime()){ 

                    //开始选择的时间小于当前的时间（日期）
                    if(this.currentDate){
                        for(let i=0;i<arr.length;i++){
                            arr[i] = -1
                        }
                        
                    }else{
                        if(this.flagDate && this.createDate(this.flagDate).getTime() < new Date(dateYear,dateMonth-1,dateDay).getTime()){
                            for(let i=0;i<arr.length;i++){
                                arr[i] = -1
                            }
                        }else{
                            let tempDate = ''

                            for(let i=0;i<this.occupyTimes.length;i++){
                                if(this.createDate(this.occupyTimes[i].date).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()){
                                    occupytime = this.occupyTimes[i].times
                                    tempDate = this.occupyTimes[i].date
                                    break
                                }
                            }

                            for(let i=0;i<occupytime.length;i++){

                                let timeArray = occupytime[i].split(':')
                                let hour = parseInt(timeArray[0])
                                let mi = parseInt(timeArray[1])

                                if(mi>=30){
                                    for(let i=hour*2+1;i<arr.length;i++){
                                        arr[i] = -1
                                    }
                                }else{

                                    for(let i=hour*2;i<arr.length;i++){
                                        arr[i] = -1
                                    }
                                }

                                this.flagDate = tempDate
                            }
                        }

                        
                    }
                    
                }
            }

            if(this.startIndex != -1 && this.endIndex != -1){ //开始时间与结束时间都已选择

                console.log('点击结束')
                occupytime = []

                for(let i=0;i<this.occupyTimes.length;i++){

                    if(this.createDate(this.occupyTimes[i].date).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()){
                        occupytime = this.occupyTimes[i].times
                        break
                    }
                }

                for(let i=0;i<occupytime.length;i++){

                    let timeArray = occupytime[i].split(':')
                    let hour = parseInt(timeArray[0])
                    let mi = parseInt(timeArray[1])

                    if(mi>=30){
                        arr[hour*2+1] = -1
                    }else{
                        arr[hour*2] = -1
                    }
                }

                if(this.createDate(this.startDate).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()  &&this.createDate(this.startDate).getTime() == this.createDate(this.endDate).getTime()){
                    arr[this.startIndex] = 11
                    for(let i=this.startIndex+1;i<this.endIndex;i++){
                        arr[i] = 10
                    }
                    arr[this.endIndex] = 12


                }

                if(this.createDate(this.startDate).getTime() < this.createDate(this.endDate).getTime()){
                    if(this.createDate(this.startDate).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()){
                        arr[this.startIndex] = 11
                        for(let i=this.startIndex+1;i<arr.length;i++){
                            arr[i] = 10
                        }
                    }

                    if(this.createDate(this.endDate).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()){
                        for(let i= 0;i<this.endIndex;i++){
                            arr[i] = 10
                        }
                        arr[this.endIndex] = 12
                        
                    }

                    if(this.createDate(this.startDate).getTime() < new Date(dateYear,dateMonth-1,dateDay).getTime() && this.createDate(this.endDate).getTime()> new Date(dateYear,dateMonth-1,dateDay).getTime()){
                        for(let i=0;i<arr.length;i++){
                            arr[i]= 10
                        }
                    }
                }


                if(this.onlyEnd){
                    if(this.createDate(this.startDate).getTime() > new Date(dateYear,dateMonth-1,dateDay).getTime()){
                        for(let i=0;i<arr.length;i++){
                            arr[i] = -1
                        }
                    }else if(this.createDate(this.startDate).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()){
                        this.currentDate = false
                        for(let i=0;i<this.startIndex;i++){
                            arr[i] = -1
                        }

                        
                        arr[this.startIndex] = 11

                        occupydate = this.startDate
                        for(let i=0;i<this.occupyTimes.length;i++){ //第一个被占用的天

                            if(this.createDate(this.occupyTimes[i].date).getTime() == this.createDate(occupydate).getTime()){
                                
                                occupytime = this.occupyTimes[i].times
                                break;
                            }
                        }

                        for(let i=0;i<occupytime.length;i++){ //被占用的时间

                            let timeArray = occupytime[i].split(':')
                            let hour = parseInt(timeArray[0])
                            let mi = parseInt(timeArray[1])

                            let startTimeArray = this.times[this.startIndex].split(':')
                            let startHour = parseInt(startTimeArray[0])
                            let startMi = parseInt(startTimeArray[0])

                            if(hour> startHour){
                                let i =0

                                if(mi>30){
                                    i = hour*2+2
                                }else{
                                    i = hour*2+1
                                }

                                for(;i<arr.length;i++){
                                    arr[i] = -1
                                }

                                this.currentDate = true

                                break
                            }
                        }
                    }else{
                        if(this.currentDate){
                            for(let i=0;i<arr.length;i++){
                                arr[i] = -1
                            }
                            
                        }else{
                            if(this.flagDate && this.createDate(this.flagDate).getTime() < new Date(dateYear,dateMonth-1,dateDay).getTime()){
                                for(let i=0;i<arr.length;i++){
                                    arr[i] = -1
                                }
                            }else{
                                let tempDate = ''

                                for(let i=0;i<this.occupyTimes.length;i++){
                                    if(this.createDate(this.occupyTimes[i].date).getTime() == new Date(dateYear,dateMonth-1,dateDay).getTime()){
                                        occupytime = this.occupyTimes[i].times
                                        tempDate = this.occupyTimes[i].date
                                        break
                                    }
                                }

                                for(let i=0;i<occupytime.length;i++){

                                    let timeArray = occupytime[i].split(':')
                                    let hour = parseInt(timeArray[0])
                                    let mi = parseInt(timeArray[1])

                                    if(mi>=30){
                                        for(let i=hour*2+1;i<arr.length;i++){
                                            arr[i] = -1
                                        }
                                    }else{

                                        for(let i=hour*2;i<arr.length;i++){
                                            arr[i] = -1
                                        }
                                    }

                                    this.flagDate = tempDate
                                }
                            }
                        }
                    }
                }
            }
            
            // return [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
            return arr
        },
        setTimeStatus(index, value){
            this.timeStatus = this.initStatus()
            this.timeTempStatus[index] = value
            this.timeStatus = this.timeTempStatus
            
        },
        createDate(str){
            let dateArray = str.split('-')
            return new Date(parseInt(dateArray[0]),parseInt(dateArray[1])-1,parseInt(dateArray[2]))
        },
        createTime(str){
            let strArray = str.split(' ')
            let dateArray = strArray[0].split('-')
            let timeArray = strArray[1].split(':')
            let yyyy = parseInt(dateArray[0])
            let MM = parseInt(dateArray[1]) - 1
            let dd = parseInt(dateArray[2])
            let HH = parseInt(timeArray[0])
            let mm = parseInt(timeArray[1])

            return new Date(yyyy, MM, dd, HH, mm)
        }
    },
    ready(){
        //获取文本框的位置
        let top = $('#'+this.id).offset().top
        let left = $('#'+this.id).offset().left

        console.log('top:'+top+',left:'+left)

        $('#'+this.id+'-picker').css({
            // 'top':top+'px',
            // 'left': left+'px',
        })

        console.log('--------------------------------------')

        console.log(this.begin)

        if(this.begin){
            let beginTime = this.createTime(this.begin)
            this.startDate = beginTime.getFullYear()+'-'+(beginTime.getMonth()+1)+'-'+beginTime.getDate()
            console.log(beginTime)
            let cur_index = -1
            let beginHour = beginTime.getHours()
            let beginMinute = beginTime.getMinutes()

            console.log(beginHour+':'+beginMinute)

            for(let i=0;i<this.times.length;i++){

                let cur_time_array = this.times[i].split(':')
                if(parseInt(cur_time_array[0])==beginHour && parseInt(cur_time_array[1])==beginMinute){
                    cur_index = i
                    break
                }
            }
            this.startIndex = cur_index
        }

        if(this.end){
            let endTime = this.createTime(this.end)
            this.endDate = endTime.getFullYear()+'-'+(endTime.getMonth()+1)+'-'+endTime.getDate()
            let cur_index = -1
            let endHour = endTime.getHours()
            let endMinute = endTime.getMinutes()

            for(let i=0;i<this.times.length;i++){
                let cur_time_array = this.times[i].split(':')
                if(parseInt(cur_time_array[0])==endHour && parseInt(cur_time_array[1])==endMinute){
                    cur_index = i
                    break
                }
            }
            this.endIndex = cur_index
        }

        if(this.onlyEnd){
            console.log('date:'+this.startDate+',time:'+this.startIndex)

            this.startClick = true
            
            if(this.endDate){
                this.date = this.createDate(this.endDate)
            }else if(this.startDate){
                this.date = this.createDate(this.startDate)
            }
        }else{
            if(this.startDate){
                this.date = this.createDate(this.startDate)
            }else if(this.endDate){
                this.date = this.createDate(this.endDate)
            }
        }

        console.log('==============================================')

        console.log('#######')
        console.log(this.times.length+','+this.timeStatus.length)
        console.log(this.date)

        /**点击时间 */
        $(document).click((e)=>{
            //  $.closest(b).length
            console.log('picker:')
            console.log($(e.target).closest('#'+this.id+'-picker').length)
            console.log($(e.target).attr('id'))
            if($(e.target).closest('#'+this.id+'-picker').length > 0 || $(e.target).attr('id') == this.id ){
                this.showPicker = true
            }else{
                this.showPicker = false
            }

            if($(e.target).attr('data-action')=='close'){
                this.showPicker = false
            }
        })
        // $('#'+this.id).blur()


    }
}
</script>

<style lang="sass">
.time-slot{
    position:relative;
    box-sizing: border-box;
}
.time-slot-picker{
    position: absolute;
    top: '';
    border: 0 !important;
    border-radius: 2px !important;
    margin: 0;
    padding: 5px;
    /*width: 400px;*/
    /*height:400px;*/
    z-index: 10;
    background: #fff;

    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.22) !important;

    border: 1px solid #eee;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    -ms-border-radius: 2px;
    -o-border-radius: 2px;
    border-radius: 2px;

    box-sizing: border-box;
}

.time-slot-picker .table{
    width: 100%;
    margin: 0;
    border-spacing: 0;
    border-collapse: collapse;
}

.time-slot-picker table tr td,.time-slot-picker table tr th{
    text-align: center;
    height:30px;
    /*border-radius: 4px;*/
    border: none;
    /*padding: 5px;*/
}
.time-slot-picker thead tr:first-child th{
    cursor: pointer;
}
.time-slot-picker .day{
    /*width: auto;*/
}
.time-slot-picker .prev:hover,.time-slot-picker .next:hover{
    background: #eee;
}

.time-slot-picker tbody tr td{
    height:40px;
    line-height:40px;
    /*padding: 5px;*/
    cursor: pointer;
    vertical-align: bottom;
    border:1px solid #eee;
    width:50px;
    overflow:hidden;
}
.time-slot-picker tbody tr td:hover{
    background:#eee;
}
.time-slot-picker tbody tr td.old{
    color:#999;
    cursor: default;
    /*text-decoration:line-through;*/
}
.time-slot-picker tbody tr td.old:hover{
    background:#fff;
}
.time-slot-picker tbody tr td.range{
    background: #ebf4f8;
    -webkit-border-radius: 0;
    -moz-border-radius: 0;
    border-radius: 0;
    /*border-left:0;*/
    /*border-right:0*/
}
.time-slot-picker tbody tr td.start{
    background: #4b8df8;
    color: #fff;
    position: relative;
    padding-top: 10px;
    line-height: 20px;

    &:after{
        display: block;
        content: '开始';
        width: 30px;
        height: 20px;
        background: red;
        color: #fff;
        position: absolute;
        top: 0;
        left: 0;
        font-size: 12px;
        padding: 0;
        margin: 0;
        line-height: 20px;
    }
}
.time-slot-picker tbody tr td.start.disabled{
    background: #3598dc;
    cursor: default;
}
.time-slot-picker tbody tr td.end{
    background: #4b8df8;
    color: #fff;
    padding-top: 10px;
    line-height: 20px;
    position: relative;

    &:after{
        display: block;
        content: '结束';
        width: 30px;
        height: 20px;
        background: red;
        color: #fff;
        position: absolute;
        top: 0;
        right: 0;
        font-size: 12px;
        padding: 0;
        margin: 0;
        line-height: 20px;
    }
}
</style>